﻿using System.Collections.Generic;
using WickedFlame.Core;
using WickedFlame.Core.History;
using WickedFlame.Core.Shapes;

namespace WickedFlame.Util.Actions
{
    public class CombineShapeAction
    {
        public bool DoAction(DrawingCanvas canvas)
        {
            bool trkOk = true;
            foreach (VectorShape shape in canvas.SelectedLayer.ShapeList.Selection)
                if (shape.SelectedTracker <= 0)
                    trkOk = false;

            if (canvas.SelectedLayer.ShapeList.SelectionCount != 2 ||
                trkOk == false)
                return false;

            PolygonShape poligon = null;
            VectorShape referenceShape = null;

            List<VectorShape> shapes = new List<VectorShape>();
            // check if there already is a Polygon in the selection
            foreach (VectorShape s in canvas.SelectedLayer.ShapeList.Selection)
            {
                shapes.Add(s);
                if (s is PolygonShape)
                    poligon = s as PolygonShape;
            }

            if (poligon != null)
            {
                shapes.Remove(poligon);
            }
            else
            {
                //create polygonshape if there is none in the selection
                foreach (VectorShape s in canvas.SelectedLayer.ShapeList.Selection)
                {
                    if (!(s is IPolygonShape))
                        continue;
                    //if (s is IPolygonShape)
                    //{
                    poligon = (s as IPolygonShape).CreatePolygon();

                    canvas.RemoveShape(s);
                    shapes.Remove(s);
                    canvas.AddShape(poligon, false);

                    referenceShape = s;

                    break;
                    //}
                }
            }

            bool ok = true;
            if (poligon != null)
            {
                try
                {
                    var command = new ShapeCombineCommand(shapes,
                        poligon, referenceShape, canvas.SelectedLayerIndex);

                    //poligon.JoinEndSegments = false;
                    foreach (VectorShape s in shapes)
                    {
                        if (!(s is IPolygonShape))
                            continue;
                        //if (s is IPolygonShape)
                        //{
                        (s as IPolygonShape).AddShapeToPoligon(poligon);
                        canvas.RemoveShape(s);
                        //}
                    }

                    command.SetNewState();
                    canvas.PushHistoryCommand(command);
                }
                catch (ShapeException)
                {
                    ok = false;
                }
            }

            DrawingCanvas.DrawTrackers();

            return ok;
        }
    }
}
